﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MachineQA.Model;
using MachineQA.DataAccess;

namespace MachineQA.DataAccess
{
    public class EnergyRepository : IEnergyRepository
    {
        readonly List<Energy> _energies;
        readonly QADatabaseEntities _entities;

        /// <summary>
        /// Creates an instance of the energy repository.
        /// </summary>
        /// <param name="entityModel">The entity model to target for the repository.</param>
        public EnergyRepository(ref QADatabaseEntities entityModel)
        {
            _energies = entityModel.Energies.ToList();
            _entities = entityModel;
        }

        #region Public Interface

        /// <summary>
        /// Event that is raised if an energy is added or removed from the repository.
        /// </summary>
        public event EventHandler<EnergyAddedOrRemovedEventArgs> EnergyAddedOrRemoved;

        /// <summary>
        /// Adds an energy to the repository.
        /// </summary>
        /// <param name="energy">The energy to add.</param>
        public void AddEnergy(Energy energy)
        {
            if (!_energies.Contains(energy))
            {
                _energies.Add(energy);
                _entities.AddToEnergies(energy);
                _entities.SaveChanges(); // persist to db.
                if (this.EnergyAddedOrRemoved != null)
                    this.EnergyAddedOrRemoved(this, new EnergyAddedOrRemovedEventArgs(energy, true));
            }
        }

        /// <summary>
        /// Removes an energy from the repository.
        /// </summary>
        /// <param name="energy">The energy to remove.</param>
        public void RemoveEnergy(Energy energy)
        {
            if (_energies.Contains(energy))
            {
                _energies.Remove(energy);
                _entities.DeleteObject(energy);
                _entities.SaveChanges(); // persist to db.
                if (this.EnergyAddedOrRemoved != null)
                    this.EnergyAddedOrRemoved(this, new EnergyAddedOrRemovedEventArgs(energy, false));
            }
        }

        /// <summary>
        /// Returns a shallow copied list of all the energies.
        /// </summary>
        /// <returns>A shallow copied list of the energies in the repository.</returns>
        public List<Energy> GetEnergies()
        {
            return new List<Energy>(_energies);
        }

        /// <summary>
        /// Checks whether or not an energy is in the repository.
        /// </summary>
        /// <param name="energy">The energy to look for.</param>
        /// <returns>Whether or not the energy is contained in the repository.</returns>
        public bool ContainsEnergy(Energy energy)
        {
            return _energies.Contains(energy);
        }

        #endregion // Public Interface
    }
}
